package com.xiaochun.hxhj;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.myview.CustomProgressDialog;
import com.myview.MarqueTextView;
import com.myview.MySeekBar;
import com.util.DensityUtil;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 速读view作为绿条背景
 */
public class FreeSpeedActivity extends BaseActivity {


    private TextView tv_text;
    private int screenwidth;
    private int screenheight;
    private TextView view_line_bg;
    private Handler handlerdelay;
    private ScrollView scrollView;
    private long contentlength = 0;
    private String contentobj;
    private int lineHeight = 33;
    private int addcount = 1;
    private String bookid = "";
    private String id = "";
    private String bookname = "";
    private String bookauthor = "";
    private String file = "";
    private JSONArray minute_num;
    private CustomProgressDialog customProgressDialog;
    private MarqueTextView tv_titlebook;
    private LinearLayout ll_rebackf;
    private MySeekBar seek_progress;
    private int changeprogress = 0;
    private TextView tv_progress_tv;
    private PopupWindow mPopupWindowtime;
    private ImageView tv_set;
    private int num1 = 300;
    private int timeting = 1000;
    private ImageView img_start;
    private boolean islongscreen = false;
    private PopupWindow mPopupResultWindow;
    public int readline = 1;
    private String locationkey = "";
    private float lineSpacingExtra = 0;
    private String suduline = "";
    private LinearLayout ll_topback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                img_start.setImageResource(R.mipmap.icon_yellow_start);
                img_start.setTag(0);
                handlerdelay.removeCallbacksAndMessages(null);
//                popbysettime();
                popbygrade(ll_topback);
            }
        });
        ll_rebackf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        img_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int tag = (int) img_start.getTag();
                if (tag == 0) {
                    img_start.setImageResource(R.mipmap.icon_yellow_stop);
                    img_start.setTag(1);
                    if (addcount == 0){
                        initLine();
                    }

                    /*60.*rowNumber/(actualSpeed/setNumber)
                    rowNumber：行数
                    actualSpeed：显示的每分钟字数
                    setNumber：每行大概有多少个字*/
                    String line = getUserInfo("suduline");
                    int suduline = 1;
                    if (line == null || "".equals(line)){
                        suduline = 1;
                    }else{
                        suduline = Integer.parseInt(line);
                    }
                    int screenwidth = getWindowManager().getDefaultDisplay().getWidth();
                    int realwidth = screenwidth - DensityUtil.dip2px(context, 20);
                    String sudusize = getUserInfo("sudusize");
                    if (sudusize == null || "".equals(sudusize)){
                        sudusize = "14";
                    }
                    int sizePx = DensityUtil.dip2px(context,Integer.parseInt(sudusize));
                    int numforline = realwidth / sizePx;//每行字数

                    int i = 60 * suduline * 1000;
                    int i1 = num1 / numforline;
                    timeting = i / i1;

                    if (FreeSpeedActivity.this.suduline == null || "".equals(FreeSpeedActivity.this.suduline)) {
                        FreeSpeedActivity.this.suduline = "1";
                    }
                    handlerdelay.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            int[] position = new int[2];
                            view_line_bg.getLocationInWindow(position);

                            Layout layout = tv_text.getLayout();
                            Rect bound = new Rect();
                            layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                            int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
                            int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
                            int scrolllength = yAxisBottom - yAxisTop;
                            if (position[1] > screenheight / 2) {
                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()) {
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_yellow_start);
                                    img_start.setTag(0);
                                    addcount = 0;
                                    return;
                                }
                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                                layoutParams.setMargins(0, yAxisTop + scrolllength * Integer.parseInt(FreeSpeedActivity.this.suduline), 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
//                                addcount++;
                                addcount = addcount + Integer.parseInt(FreeSpeedActivity.this.suduline);
                                if (lineSpacingExtra > 2) {
                                    int i = scrolllength * Integer.parseInt(FreeSpeedActivity.this.suduline);
                                    scrollView.scrollBy(0, scrolllength * Integer.parseInt(FreeSpeedActivity.this.suduline));
                                } else {
                                    int i = lineHeight * Integer.parseInt(FreeSpeedActivity.this.suduline);
                                    scrollView.scrollBy(0, lineHeight * Integer.parseInt(FreeSpeedActivity.this.suduline));
                                }
                                handlerdelay.postDelayed(this, timeting);

                            } else {
                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()) {
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_yellow_start);
                                    img_start.setTag(0);
                                    addcount = 0;
                                    return;
                                }
                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                                layoutParams.setMargins(0, yAxisTop + scrolllength * Integer.parseInt(FreeSpeedActivity.this.suduline), 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
//                                addcount++;
                                addcount = addcount + Integer.parseInt(FreeSpeedActivity.this.suduline);
                                handlerdelay.postDelayed(this, timeting);

                            }
                        }
                    }, timeting);
                } else {
                    handlerdelay.removeCallbacksAndMessages(null);
                    img_start.setImageResource(R.mipmap.icon_yellow_start);
                    img_start.setTag(0);
                }

            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_freespeed;
    }

    @Override
    protected void initView() {
        changeTitle("王冰寒");
//        saveNoticeList("name", "王冰寒");
        bookid = getIntent().getStringExtra("id");
        locationkey = "sudulocation" + bookid;
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 屏幕宽度（像素）
        screenwidth = metric.widthPixels;
        // 屏幕高度（像素）
        screenheight = metric.heightPixels;

        ll_topback = findViewById(R.id.ll_topback);
        tv_set = findViewById(R.id.tv_set);
        tv_progress_tv = findViewById(R.id.tv_progress_tv);
        ll_rebackf = findViewById(R.id.ll_rebackf);
        scrollView = findViewById(R.id.scrollView);
        tv_titlebook = findViewById(R.id.tv_titlebook);
        tv_text = findViewById(R.id.tv_text);
        img_start = findViewById(R.id.img_start);
        img_start.setTag(0);
        view_line_bg = findViewById(R.id.view_line_bg);
        seek_progress = findViewById(R.id.seek_progress);
        seek_progress.setOnSeekBarChangeListener(mSeekBarListener);
        handlerdelay = new Handler();

        suduline = getUserInfo("suduline");
        if (suduline == null || "".equals(suduline)) {
            suduline = "1";
        }


        getData();


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
        suduline = getUserInfo("suduline");
        if (suduline == null || "".equals(suduline)) {
            suduline = "1";
        }
        lineHeight = tv_text.getLineHeight();
        float lineSpacingExtra = tv_text.getLineSpacingExtra();

        Layout layout = tv_text.getLayout();
        Rect bound = new Rect();
        if (addcount == 0) {
            layout.getLineBounds(addcount, bound);//获取该行的Bound区域
        } else {
            layout.getLineBounds(addcount - 1, bound);//获取该行的Bound区域
        }
        int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
        int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
        int scrolllength = yAxisBottom - yAxisTop;


        if (lineSpacingExtra > 2) {
            islongscreen = true;
            int v = (int) (lineSpacingExtra - 2);
            lineHeight = lineHeight + 8;
            layoutParams.height = scrolllength * Integer.parseInt(suduline);
        } else {
            islongscreen = false;
            layoutParams.height = scrolllength * Integer.parseInt(suduline);
        }

        view_line_bg.setLayoutParams(layoutParams);
        int[] position = new int[2];
        view_line_bg.getLocationInWindow(position);
        System.out.println("getLocationInWindow:" + position[0] + "," + position[1]);

    }

    @Override
    protected void initData() {

    }

    private void GetByHttpClient(final String url) {
        new Thread() {
            public void run() {
                try {

                    /**
                     * OkHttpClient 的Get请求
                     */
                    //创建okHttpClient对象
                    OkHttpClient mOkHttpClient;
                    mOkHttpClient = new OkHttpClient();
                    //创建一个Request
                    final Request request = new Request.Builder()
                            .url(url)
                            .build();
                    //new call
                    Call call = mOkHttpClient.newCall(request);
                    //请求加入调度
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

//                            String str = new String(new String(response.body().bytes(), "gb2312"));
//                            String htmlStr = str;
                            String htmlStr = response.body().string();

                            String oldstr1 = "\t";
                            String newstr1 = "";
                            htmlStr = htmlStr.replace(oldstr1, newstr1);
//                            String oldstr3 = " ";
//                            String newstr3 = "";
//                            htmlStr = htmlStr.replace(oldstr3, newstr3);


                            String oldstr = "\r\n\r\n";
                            String newstr = "\r\n";
                            htmlStr = htmlStr.replace(oldstr, newstr);
                            htmlStr = htmlStr.replace(oldstr, newstr);
                            htmlStr = htmlStr.replace(oldstr, newstr);
                            htmlStr = htmlStr.replace(oldstr, newstr);
                            htmlStr = htmlStr.replace(oldstr, newstr);

                            if (htmlStr.startsWith("\r\n")){
                                htmlStr = htmlStr.substring(4, htmlStr.length());
                            }
                            if (htmlStr.startsWith("\r\n")){
                                htmlStr = htmlStr.substring(4, htmlStr.length());
                            }
                            if (htmlStr.startsWith("\r\n")){
                                htmlStr = htmlStr.substring(4, htmlStr.length());
                            }

//                            MyLog.e("jorli=====>", htmlStr);
                            Message msg = new Message();
                            msg.arg1 = 10;
                            msg.obj = htmlStr;
                            if (handlerData != null) {
                                handlerData.sendMessage(msg);
                            }
                        }

                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }


    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/speed/detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", bookid);
        paramsMap.put("token", token);
        MyLog.e("速读详情", bookid + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                   /* "id": 12,
                            "name": "巴黎圣母院",
                            "image": "https://oss.bigchun.com/fastmemory/uploads/20200603/462eb8dbe419a521ea6887acca4e88cf.jpg",
                            "author": "维克多·雨果",
                            "minute_num": [
                    "约34万字"
        ],
                    "file": "https://oss.bigchun.com/fastmemory/uploads/20200603/991fa046c50fde940b59fcbc4fa3831a.txt",*/
                    id = data.getString("id");
                    bookname = data.getString("name");
                    bookauthor = data.getString("author");
                    file = data.getString("file");
                    minute_num = data.getJSONArray("minute_num");


                    msg.arg1 = 2;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 进度拖动条监听器
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
        // 通知进度已经被修改
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                changeprogress = progress;
            }
        }

        // 通知用户已经开始一个触摸拖动手势
        public void onStartTrackingTouch(SeekBar seekBar) {

            img_start.setImageResource(R.mipmap.icon_yellow_start);
            img_start.setTag(0);
            handlerdelay.removeCallbacksAndMessages(null);
        }

        // 通知用户触摸手势已经结束
        public void onStopTrackingTouch(SeekBar seekBar) {
            //最小300  最大5000    总长度是4700   每一个格子是47
            num1 = 47 * changeprogress;
            num1 = num1 + 300;
            int jishu = num1 / 100;
            int startnum = jishu * 100;
            int jishu2 = jishu + 1;
            int endnum = jishu2 * 100;
            tv_progress_tv.setText(startnum + "~" + endnum + "字/分钟");


        }
    };

    /**
     * 弹出搜索框
     */
    private void popbysettime(int type) {


        int max = 100;
        int maxline = 10;
        int min = 1;

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_set_zi, null);

        EditText et_zishu = popupWindow.findViewById(R.id.et_zishu);
        TextView tv_cancle = popupWindow.findViewById(R.id.tv_cancle);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        TextView tv_title = popupWindow.findViewById(R.id.tv_title);
        if (type == 1) {
            //字号
            tv_title.setText("设置字号");
            et_zishu.setHint("需要设置的字号");
        } else if (type == 2) {
            //行数
            tv_title.setText("设置行数");
            et_zishu.setHint("需要设置的行数");
        }

        et_zishu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = et_zishu.getText().toString().trim();
                if (s.length() > 0) {
                    tv_sure.setTextColor(context.getResources().getColor(R.color.color4272DB));
                } else {
                    tv_sure.setTextColor(context.getResources().getColor(R.color.color999));
                }

                if (type == 1) {
                    if (i >= 0) { //从一输入就开始判断，
                        if (min != -1 && max != -1) {
                            try {
                                int num = Integer.parseInt(s.toString());
                                //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                                if (num > max) {
                                    s = String.valueOf(max);//如果大于max，则内容为max
                                    et_zishu.setText(s);

                                } else if (num < min) {
                                    s = String.valueOf(min);//如果小于min,则内容为min
                                    et_zishu.setText(s);
                                }
                            } catch (NumberFormatException e) {
                                MyLog.e("ontextchanged", "==" + e.toString());
                            }
                            //edittext中的数字在max和min之间，则不做处理，正常显示即可。
                            return;
                        }
                    } else {
                    }
                } else if (type == 2) {
                    if (i >= 0) { //从一输入就开始判断，
                        if (min != -1 && maxline != -1) {
                            try {
                                int num = Integer.parseInt(s.toString());
                                //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                                if (num > maxline) {
                                    s = String.valueOf(maxline);//如果大于max，则内容为max
                                    et_zishu.setText(s);

                                } else if (num < min) {
                                    s = String.valueOf(min);//如果小于min,则内容为min
                                    et_zishu.setText(s);
                                }
                            } catch (NumberFormatException e) {
                                MyLog.e("ontextchanged", "==" + e.toString());
                            }
                            //edittext中的数字在max和min之间，则不做处理，正常显示即可。
                            return;
                        }
                    } else {
                    }
                }


            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
//        et_zishu.setTextWatcher();

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindowtime.dismiss();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_zishu.getText().toString().trim();
                if ("".equals(trim)) {
//                    ToastUtils.show("请输入需要设置的字号");
                } else {
                    savelable();
                    lineHeight = tv_text.getLineHeight();

                    Layout layout = tv_text.getLayout();
                    Rect bound = new Rect();
                    layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                    /*if (addcount == 0) {
                        layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                    } else {
                        layout.getLineBounds(addcount - 1, bound);//获取该行的Bound区域
                    }*/
                    int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
                    int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
                    int scrolllength = yAxisBottom - yAxisTop;

                    if (type == 1) {
                        saveUserInfo("sudusize", trim);
                        int tvsize = Integer.parseInt(trim);
                        isfirst = true;
                        tv_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, tvsize);
                        view_line_bg.setVisibility(View.VISIBLE);
                        float lineSpacingExtra = tv_text.getLineSpacingExtra();
                        if (lineSpacingExtra > 2) {
                            islongscreen = true;
                            int v = (int) (lineSpacingExtra - 2);
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            lineHeight = lineHeight + 8;
                            layoutParams.height = scrolllength * Integer.parseInt(suduline);
                            view_line_bg.setLayoutParams(layoutParams);
                        } else {
                            islongscreen = false;
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            layoutParams.height = scrolllength;
                            view_line_bg.setLayoutParams(layoutParams);
                        }

                        /*int sudulocation = Integer.parseInt(getUserInfo(locationkey));
                        int end;
                        int start = 0;
                        for (int i = 0; i < tv_text.getLineCount(); i++) {
                            end = layout.getLineEnd(i);
                            if (sudulocation >= start && sudulocation <= end) {
                                isfirst = true;
                                saveUserInfo(locationkey, sudulocation + "");
                                initLoca();
                                break;
                            }
                            start = end;
                        }*/
                    } else if (type == 2) {
                        saveUserInfo("suduline", trim);
                        view_line_bg.setVisibility(View.VISIBLE);
                        float lineSpacingExtra = tv_text.getLineSpacingExtra();
                        float asdsa = tv_text.getLineSpacingMultiplier();
                        if (lineSpacingExtra > 2) {
                            islongscreen = true;
                            int v = (int) (lineSpacingExtra - 2);
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            lineHeight = lineHeight + 8;
                            layoutParams.height = scrolllength * Integer.parseInt(trim);
                            view_line_bg.setLayoutParams(layoutParams);
                        } else {
                            islongscreen = false;
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            layoutParams.height = scrolllength * Integer.parseInt(trim);
                            view_line_bg.setLayoutParams(layoutParams);
                        }

                        int sudulocation = Integer.parseInt(getUserInfo(locationkey));
                        String text = tv_text.getText().toString();
                        int end;
                        int start = 0;
                        for (int i = 0; i < tv_text.getLineCount(); i++) {
                            end = layout.getLineEnd(i);
                            if (sudulocation >= start && sudulocation <= end) {
                                isfirst = true;
                                saveUserInfo(locationkey, end + "");
                                initLoca();
                                break;
                            }
                            start = end;
                        }
                    }


                    mPopupWindowtime.dismiss();

                }
            }
        });

        mPopupWindowtime = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindowtime.getWidth();
        int mPopupWindowHeight = mPopupWindowtime.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindowtime.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowtime.setOutsideTouchable(true);
        mPopupWindowtime.setTouchable(true);
        mPopupWindowtime.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindowtime.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindowtime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerdelay.removeCallbacksAndMessages(null);
    }

    public Handler handlerData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    ToastUtils.show(R.string.net_error);
                    break;
                case 2:
                    String num = "";
                    if (minute_num.length() > 0) {
                        try {
                            num = minute_num.getString(0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    String title = bookname + num + " 作者：" + bookauthor;
                    SpannableString spanString = new SpannableString(title);
                    //再构造一个改变字体颜色的Span
                    ForegroundColorSpan span = new ForegroundColorSpan(Color.BLACK);
                    //将这个Span应用于指定范围的字体    前包括后不包括
                    spanString.setSpan(span, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    AbsoluteSizeSpan spansize = new AbsoluteSizeSpan(36);
                    spanString.setSpan(spansize, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_titlebook.setText(spanString);
                    /*tv_titlebook.setText(title);
                    tv_titlebook.setFocusable(true);*/
                    GetByHttpClient(file);


                    break;
                case 3:
                    break;
                case 4:


                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:

                    break;
                case 8:


                    break;
                case 9:

                    break;
                case 10:
                    String sudusize = getUserInfo("sudusize");
                    if (!"".equals(sudusize)) {
                        int ssize = Integer.parseInt(sudusize);
                        tv_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, ssize);
                    }
                    contentobj = (String) msg.obj;
                    contentlength = contentobj.length();
                    tv_text.setText(contentobj);
                    lineHeight = tv_text.getLineHeight();


                    view_line_bg.setVisibility(View.VISIBLE);
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    lineSpacingExtra = tv_text.getLineSpacingExtra();
                    float lineMultiplier = tv_text.getLineSpacingMultiplier();

                    float asdsa = tv_text.getLineSpacingMultiplier();
                    suduline = getUserInfo("suduline");
                    if (suduline == null || "".equals(suduline)) {
                        suduline = "1";
                    }
                    if (lineSpacingExtra > 2) {
                        islongscreen = true;
                        int v = (int) (lineSpacingExtra - 2);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();

                        lineHeight = lineHeight + 8;
                        layoutParams.height = lineHeight * Integer.parseInt(suduline);
                        view_line_bg.setLayoutParams(layoutParams);
                    } else {
                        islongscreen = false;
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        layoutParams.height = lineHeight * Integer.parseInt(suduline);
                        view_line_bg.setLayoutParams(layoutParams);
                    }

                    initLoca();
                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id", "").commit();
                    sharedPreferences.edit().putString("username", "").commit();
                    sharedPreferences.edit().putString("nickname", "").commit();
                    sharedPreferences.edit().putString("mobile", "").commit();
                    sharedPreferences.edit().putString("avatar", "").commit();
                    sharedPreferences.edit().putString("score", "").commit();
                    sharedPreferences.edit().putString("student_id", "").commit();
                    sharedPreferences.edit().putString("is_bind_wx", "").commit();
                    sharedPreferences.edit().putString("token", "").commit();
                    finish();
                    break;
                case 13:

                    break;

            }

        }
    };

    /**
     * 弹出搜索框收藏
     */
    private void popbygrade(View viewlayout) {
        if (mPopupResultWindow != null) {
            if (mPopupResultWindow.isShowing()) {
                mPopupResultWindow.dismiss();
            }
        }

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.layout_pop_sudu, null);
        LinearLayout ll_pop_setsize = popupWindow.findViewById(R.id.ll_pop_setsize);
        LinearLayout ll_pop_saveshuqian = popupWindow.findViewById(R.id.ll_pop_saveshuqian);
        LinearLayout ll_pop_setline = popupWindow.findViewById(R.id.ll_pop_setline);
        ll_pop_setline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupResultWindow != null) {
                    if (mPopupResultWindow.isShowing()) {
                        mPopupResultWindow.dismiss();
                    }
                }
                if (DensityUtil.isFastDoubleClick()) {
                    return;
                }
                popbysettime(2);
            }
        });
        ll_pop_setsize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupResultWindow != null) {
                    if (mPopupResultWindow.isShowing()) {
                        mPopupResultWindow.dismiss();
                    }
                }
                if (DensityUtil.isFastDoubleClick()) {
                    return;
                }
                popbysettime(1);
            }
        });
        ll_pop_saveshuqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupResultWindow != null) {
                    if (mPopupResultWindow.isShowing()) {
                        mPopupResultWindow.dismiss();
                    }
                }
                savelable();
                ToastUtils.show("书签保存成功");
            }
        });

        mPopupResultWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupResultWindow.getWidth();
        int mPopupWindowHeight = mPopupResultWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupResultWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupResultWindow.setOutsideTouchable(true);
        mPopupResultWindow.setTouchable(true);
        mPopupResultWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupResultWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupResultWindow.showAtLocation(viewlayout,
                    Gravity.BOTTOM,
                    0,
                    572);
//            mPopupResultWindow.showAsDropDown(viewlayout, -100, 0);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupResultWindow.showAtLocation(viewlayout,
                    Gravity.BOTTOM,
                    0,
                    572);
//            mPopupResultWindow.showAsDropDown(viewlayout, -100, 0);
        }
        mPopupResultWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    public void savelable() {
        Layout layout = tv_text.getLayout();
        int end;
        end = layout.getLineEnd(addcount);
        saveUserInfo(locationkey, end + "");

    }

    boolean isfirst = true;

    public void initLoca() {
        tv_text.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override

            public void onGlobalLayout() {
                if (isfirst) {
                    isfirst = false;
                    String sudulocation1 = getUserInfo(locationkey);
                    int sudulocation = 0;
                    if (!"".equals(sudulocation1)) {
                        sudulocation = Integer.parseInt(sudulocation1);
                    }
                    Layout layout = tv_text.getLayout();
                    String text = tv_text.getText().toString();
                    int end;
                    int start = 0;
                    for (int i = 0; i < tv_text.getLineCount(); i++) {
                        end = layout.getLineEnd(i);
                        if (sudulocation >= start && sudulocation <= end) {
                            addcount = i;
                            break;
                        }
                        start = end;
                        float widthnew = layout.getLineWidth(i); //指定行的宽度

                    }
                    int[] position = new int[2];
                    view_line_bg.getLocationInWindow(position);

                    Rect bound = new Rect();
                    layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                    /*if (addcount == 0) {
                        layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                    } else {
                        layout.getLineBounds(addcount - 1, bound);//获取该行的Bound区域
                    }*/
                    int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
                    int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
                    int scrolllength = yAxisBottom - yAxisTop;

                    if (position[1] > screenheight / 2) {

                        int i1 = scrolllength * addcount;
                        if (i1 > tv_text.getHeight()) {
                            handlerdelay.removeCallbacksAndMessages(null);
                            img_start.setImageResource(R.mipmap.icon_yellow_start);
                            img_start.setTag(0);
                            addcount = 0;
                            return;
                        }

                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        layoutParams.setMargins(0, yAxisTop + scrolllength * 2, 0, 0);
                        view_line_bg.setLayoutParams(layoutParams);
                        int i4 = yAxisTop + (int) lineSpacingExtra;
                        scrollView.scrollTo(0, i4);
                    } else {
                        int i1 = lineHeight * addcount;
                        if (i1 > tv_text.getHeight()) {
                            handlerdelay.removeCallbacksAndMessages(null);
                            img_start.setImageResource(R.mipmap.icon_yellow_start);
                            img_start.setTag(0);
                            addcount = 0;
                            return;
                        }
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        layoutParams.setMargins(0, yAxisTop, 0, 0);
                        view_line_bg.setLayoutParams(layoutParams);
                        int i4 = yAxisTop + (int) lineSpacingExtra;
                        scrollView.scrollTo(0, i4);
                    }

                }
            }


        });


    }


    public float getCharacterWidth(TextView tv) {
        if (null == tv)
            return 0f;
        return getCharacterWidth(tv.getText().toString())
                * tv.getScaleX();
    }


    // 获取每个字符的宽度主方法：
    public float getCharacterWidth(String text) {
        String sudusize = getUserInfo("sudusize");
        float size = Float.parseFloat(sudusize);
        text = "中华人民共和国";

        if (null == text || "".equals(text))
            return 0;
        float width = 0;
        Paint paint = new Paint();
        paint.setTextSize(size);
        float text_width = paint.measureText(text);// 得到总体长度
        width = text_width / text.length();// 每一个字符的长度

        Toast.makeText(this, "" + width, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "" + text_width, Toast.LENGTH_SHORT).show();
        return width;
    }

    @Override
    protected void onPause() {
        super.onPause();
        handlerdelay.removeCallbacksAndMessages(null);
        img_start.setImageResource(R.mipmap.icon_yellow_start);
        img_start.setTag(0);
    }

    public void initLine(){
        addcount = 0;
        Layout layout = tv_text.getLayout();
        Rect bound = new Rect();
        layout.getLineBounds(addcount, bound);//获取该行的Bound区域
        int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
        int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
        int scrolllength = yAxisBottom - yAxisTop;
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
        layoutParams.setMargins(0, yAxisTop, 0, 0);
        view_line_bg.setLayoutParams(layoutParams);
        scrollView.scrollTo(0, 0);
    }
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,FreeSpeedActivity.this,tv_progress_tv);
//            popbyexit(type);
        }
    }
}
